#!/bin/sh

export XDG_CACHE_HOME=$SNAP_USER_COMMON/.cache
mkdir -p $XDG_CACHE_HOME
export GIO_MODULE_DIR=$XDG_CACHE_HOME/gio-modules
export XDG_DATA_DIRS="$SNAP/usr/share"
export FWUPD_LOCKDIR=/run/lock/snap.fwupd
export FWUPD_POLKIT_NOCHECK=1
export FWUPD_HOSTFS_ROOT=/var/lib/snapd/hostfs

#determine architecture
if [ "$SNAP_ARCH" = "amd64" ]; then
  ARCH="x86_64-linux-gnu"
elif [ "$SNAP_ARCH" = "armhf" ]; then
  ARCH="arm-linux-gnueabihf"
elif [ "$SNAP_ARCH" = "arm64" ]; then
  ARCH="aarch64-linux-gnu"
else
  ARCH="$SNAP_ARCH-linux-gnu"
fi

# re-generate gio modules in local cache
needs_update=true
if [ -f $SNAP_USER_DATA/.last_revision ]; then
  # shellcheck source=/dev/null
  . $SNAP_USER_DATA/.last_revision 2>/dev/null
fi
if [ "$SNAP_DESKTOP_LAST_REVISION" = "$SNAP_REVISION" ]; then
  needs_update=false
fi
if [ $needs_update = true ]; then
  if [ -f $SNAP/usr/lib/$ARCH/glib-2.0/gio-querymodules ]; then
    rm -rf $GIO_MODULE_DIR
    mkdir -p $GIO_MODULE_DIR
    ln -s $SNAP/usr/lib/$ARCH/gio/modules/*.so $GIO_MODULE_DIR
    $SNAP/usr/lib/$ARCH/glib-2.0/gio-querymodules $GIO_MODULE_DIR
  fi
  echo "SNAP_DESKTOP_LAST_REVISION=$SNAP_REVISION" > $SNAP_USER_DATA/.last_revision
fi

exec "$@"
